<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use Tymon\JWTAuth\JWTAuth;

class AuthController extends Controller
{
    protected $auth;
    public function __construct(JWTAuth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        if(Input::has('account')&&Input::has('password')){
            $credentials = request(['account', 'password']);
            if($credentials){
                if (!$token = $this->auth->attempt($credentials)) {
                    return $this->apiReturn(102,'账号或密码错误!',$credentials->account);
                }
                return response()->json([
                    'code'=>101,
                    'msg'=>'登录成功',
                    'data'=>$this->tokenData($token)
                ]);
            }else
                return $this->apiReturn(103,'账号或密码为空');
        }else
            return $this->apiReturn(104,'检查参数');
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function user()
    {
        return response()->json(['auth(api):'=>auth('api')->user(),'authenticate:'=>$this->auth->authenticate(),'this->auth:'=>$this->auth->user()]);
    }


    public function checkToken(){

        return $this->apiReturn(1000,'验证通过');
    }
    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        $token = $this->auth->getToken();
        $this->auth->invalidate($token);
        //Auth::guard('api')->logout();
        return $this->apiReturn(101,'退出成功');
    }

    /**
     * Refresh a token.
     * 刷新token,如果开启黑名单，以前的token便会失效。
     * 值得注意的是用上面的getToken再获取一次Token并不算做刷新，两次获得的Token是并行的，即两个都可用。
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return auth('api')->refresh();
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function tokenData($token)
    {
        $arry = [
            'access_token' => 'Bearer '.$token,
            'expires_in' => auth('api')->factory()->getTTL() * 60,
            'user'=>$this->auth->user()
        ];
        return $arry;
    }
}
